package com.bc.commoncore.security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * AES加解密
 * 窦海超  2016年5月25日 17:54:03删除
 *
 * @author talver
 */
public class AES {
    private final static String AES_KEY = "k;)*(+nmjdsf$#@d";
    private final static String UTF_8 = "UTF-8";

    /**
     * AES加密
     *
     * @param str 待加密字符串
     * @return 加密后字符串
     */
    public static String aesEncrypt(String str) {
        try {
            return aesEncrypt(AES_KEY, str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * AES解密
     *
     * @param str 待解密字符串
     * @return 解密后字符串
     */
    public static String aesDecrypt(String str) {
        try {
            return aesDecrypt(AES_KEY, str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * AES加密
     *
     * @param str 待加密字符串
     * @return 加密后字符串
     */
    public static String aesEncrypt(String aes_KEY, String str) {
        try {
            if (str == null || str.isEmpty()) {
                return "";
            }
            str = new String(str.getBytes(UTF_8), UTF_8);
            String password = aes_KEY;
            SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] bs = cipher.doFinal(str.getBytes("UTF-8"));
            byte[] bs64 = Base64.getEncoder().encode(bs);
            String strTmp = new String(bs64);
            return strTmp;

        } catch (Exception e) {
            throw new RuntimeException("AES加密时异常" + e.getMessage());
        }
    }

    /**
     * AES解密
     *
     * @param str 待解密字符串
     * @return 解密后字符串
     */
    public static String aesDecrypt(String aes_KEY, String str) {
        try {
            if (str == null || str.isEmpty()) {
                return "";
            }
            String password = aes_KEY;
            SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] bs = Base64.getDecoder().decode(str.replace(" ", "+"));
            String strTmp = new String(cipher.doFinal(bs), "UTF-8");
            return strTmp;

        } catch (Exception ex) {
            throw new RuntimeException("AES解密时异常" + ex.getMessage());
        }
    }

    /** public static void main(String[] args) {
     String str = "掌合天下";
     String encrypt = aesEncrypt(str);
     System.out.println("99999999999" + encrypt);
     System.out.println("11111111111" + aesDecrypt(encrypt));

     } **/
}